package com.yanqu.road.server.manger.activity.evefeast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.activity.evefeast.EveFeastConfigDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.evefeast.EveFeastBlock;
import com.yanqu.road.entity.activity.evefeast.EveFeastGameData;
import com.yanqu.road.entity.activity.evefeast.EveFeastItem;
import com.yanqu.road.entity.activity.evefeast.config.EveFeastAchieveConfig;
import com.yanqu.road.entity.activity.evefeast.config.EveFeastBuffConfig;
import com.yanqu.road.entity.activity.evefeast.config.EveFeastMissionConfig;
import com.yanqu.road.entity.activity.evefeast.config.EveFeastObjectConfig;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.logic.activity.evefeast.EveFeastConfig;
import com.yanqu.road.logic.activity.evefeast.EveFeastGameLogic;
import com.yanqu.road.logic.activity.evefeast.EveFeastShowInfo;
import com.yanqu.road.logic.activity.evefeast.enums.eEveFeastShowType;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.pb.EveFeastPb;
import com.yanqu.road.pb.activity.EveFeastProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.game.service.GameService;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.evefeast.EveFeastModule;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.evefeast.service.EveFeastWatchMaxScoreItemsServiceCmd;
import com.yanqu.road.server.manger.activity.silkroad.service.SilkRoadLookOtherReflicServiceCmd;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.property.Property;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class EveFeastMgr extends TempMgr {

    private static EveFeastConfig config;
    private static ActivityInfo activityInfo;

    /**
     * 引导用的消息
     */
    private static List<EveFeastProto.EveFeastStartRandomRespMsg> guideMsgList = new ArrayList<>();
    /**
     * 引导完的初始盘面
     */
    private static EveFeastGameData initGameData = null;


    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    public static void reloadActivityData() {
        getLogger().info("reload evefeast activity start");
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.EveFeast.getValue());
        if (openActivityInfoList.isEmpty()) {
            getLogger().info("no evefeast Activity in show time");
            activityInfo = null;
            config = null;
            guideMsgList = new ArrayList<>();
            initGameData = null;
        } else {
            ActivityInfo tempActivityInfo = openActivityInfoList.get(0);
            List<Integer> activityIdList = new ArrayList<>();
            int acitivityId = tempActivityInfo.getActivityId();
            activityIdList.add(acitivityId);
            Map<String, ActivityConfig> activityConfigMap = ActivityMgr.getActivityConfigMap(acitivityId);
            EveFeastConfig tempConfig = new EveFeastConfig(acitivityId);
            tempConfig.parseConfig(activityConfigMap);
            tempConfig.setObjectConfigMap(new EveFeastConfigDaoImpl().getEveFeastObjectConfigMap(acitivityId));
            tempConfig.setBuffConfigMap(new EveFeastConfigDaoImpl().getEveFeastBuffConfigMap(acitivityId));
            tempConfig.setMissionConfigMap(new EveFeastConfigDaoImpl().getEveFeastMissionConfigMap(acitivityId));
            tempConfig.setAchieveConfigMap(new EveFeastConfigDaoImpl().getEveFeastAchieveConfigMap(acitivityId));

            tempConfig.initMissionObjectWeight();

            activityInfo = tempActivityInfo;
            config = tempConfig;
            initGuideMsg();
        }

        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            player.getModule(EveFeastModule.class).initUserData();
            player.getModule(EveFeastModule.class).syncUserMsg();
            player.getModule(EveFeastModule.class).syncConfigMsg();
        }


        getLogger().info("reload evefeast activity end");
    }

    public static void initService(GameService syncMessageService) {
        syncMessageService.addGameServiceCommand(GameProtocol.S_EVEFEAST_WATCH_MAX_SCORE_ITEMS, new EveFeastWatchMaxScoreItemsServiceCmd());
    }

    public static EveFeastConfig getConfig() {
        return config;
    }

    public static ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public static EveFeastProto.EveFeastConfigSyncMsg.Builder getConfigMsg(String language){
        if (config == null) {
            return null;
        }
        EveFeastProto.EveFeastConfigSyncMsg configMsg = config.getConfigMsg(language);
        if (configMsg == null) {
            synchronized (config){
                configMsg = config.getConfigMsg(language);
                if (configMsg == null) {
                    configMsg = initConfigMsg(language).build();
                    config.setConfigMsg(language, configMsg);
                }
            }
        }
        return configMsg.toBuilder();
    }

    public static EveFeastProto.EveFeastConfigSyncMsg.Builder initConfigMsg(String language) {
        EveFeastProto.EveFeastConfigSyncMsg.Builder builder = EveFeastProto.EveFeastConfigSyncMsg.newBuilder();
        builder.setActivityId(activityInfo.getActivityId());
        for (EveFeastObjectConfig objectConfig : config.getObjectConfigMap().values()) {
            EveFeastProto.EveFeastConfigObjectTemp.Builder objectTemp = EveFeastProto.EveFeastConfigObjectTemp.newBuilder();
            objectTemp.setId(objectConfig.getObjectId());
            objectTemp.setName(ServerLanguageMgr.getContent(objectConfig.getName(), language));
            objectTemp.setDesc(ServerLanguageMgr.getContent(objectConfig.getDesc(), language));
            objectTemp.setQuality(objectConfig.getQuality());
            objectTemp.setType(objectConfig.getType());
            objectTemp.setBaseScore(objectConfig.getBaseScore());
            objectTemp.setWeight(objectConfig.getWeight());
            objectTemp.setConditionParam(objectConfig.getConditionParam());
            objectTemp.setEffectParam(objectConfig.getEffectParam());
            objectTemp.setSect(objectConfig.getSect());
            objectTemp.setTieItem(objectConfig.getTieItem());
            objectTemp.setButtonInfo(objectConfig.getButtonInfo());
            objectTemp.setLimitNum(objectConfig.getLimitNum());

            builder.addConfigItem(objectTemp);
        }

        for (EveFeastBuffConfig buffConfig : config.getBuffConfigMap().values()) {
            EveFeastProto.EveFeastConfigBuffTemp.Builder buffTemp = EveFeastProto.EveFeastConfigBuffTemp.newBuilder();
            buffTemp.setGreetingId(buffConfig.getGreetingId());
            buffTemp.setName(ServerLanguageMgr.getContent(buffConfig.getName(), language));
            buffTemp.setDesc(ServerLanguageMgr.getContent(buffConfig.getDesc(), language));
            buffTemp.setQuality(buffConfig.getQuality());
            buffTemp.setWeight(buffConfig.getWeight());
            buffTemp.setWeightChange(buffConfig.getWeightChange());
            buffTemp.setSkill(buffConfig.getSkill());
            buffTemp.setIcon(buffConfig.getIcon());
            buffTemp.setButtonInfo(buffConfig.getButtonInfo());

            builder.addConfigBuff(buffTemp);
        }

        for (EveFeastMissionConfig missionConfig : config.getMissionConfigMap().values()) {
            EveFeastProto.EveFeastConfigMissionTemp.Builder missionTemp = EveFeastProto.EveFeastConfigMissionTemp.newBuilder();
            missionTemp.setTurnId(missionConfig.getTurnId());
            missionTemp.setMissionId(missionConfig.getMission());
            missionTemp.setTurn(missionConfig.getTurn());
            missionTemp.setRound(missionConfig.getRound());
            missionTemp.setCondition(missionConfig.getCondition());
            missionTemp.setWeightParam(missionConfig.getWeightParam());
            missionTemp.setBuffWeightParam(missionConfig.getBuffWeightParam());
            missionTemp.setExItem(missionConfig.getExItem());

            builder.addConfigMission(missionTemp);
        }

        for (EveFeastAchieveConfig achieveConfig : config.getAchieveConfigMap().values()) {
            EveFeastProto.EveFeastConfigAchieveTemp.Builder achieveTemp = EveFeastProto.EveFeastConfigAchieveTemp.newBuilder();
            achieveTemp.setId(achieveConfig.getId());
            achieveTemp.setType(achieveConfig.getType());
            achieveTemp.setCondition(achieveConfig.getCondition());

            builder.addConfigAchieve(achieveTemp);
        }

        return builder;
    }

    /**
     * 游戏中成就检查
     * @param achieveId
     * @return
     */
    public static boolean isAchieveActive(Property itemProperty, int achieveId) {
        if (config == null) {
            return false;
        }

        EveFeastAchieveConfig achieveConfig = config.getAchieveConfig(achieveId);
        if (achieveConfig == null) {
            return false;
        }

        Property conditionProperty = achieveConfig.getConditionProperty();
        for (Map.Entry<Integer, BigInteger> entry : itemProperty.getGoods().entrySet()) {
            int itemId = entry.getKey();
            int num = entry.getValue().intValue();
            if (!conditionProperty.getGoods().containsKey(itemId)) {
                continue;
            }
            int checkNum = conditionProperty.getCountByGoodsId(itemId).intValue();
            if (checkNum <= 0) {
                continue;
            }
            if (num >= checkNum) {
                conditionProperty.removeProperty(itemId);
            }
        }

        return conditionProperty.isNothing();

    }

    /**
     * 生成新手引导数据
     */
    public static void initGuideMsg() {
        if (config == null) {
            return;
        }
        EveFeastMissionConfig missionConfig = config.getMissionConfigByTurn(0, 1);
        if (missionConfig == null) {
            return;
        }
        EveFeastGameData gameData = new EveFeastGameData();
        gameData.setTurnId(missionConfig.getTurnId());
        gameData.setRound(1);

        List<List<EveFeastBlock>> listList = new ArrayList<>();
        //初始化格子
        for (int y = 0; y < EveFeastGameLogic.HIGH; y++) {
            List<EveFeastBlock> yList = new ArrayList<>(EveFeastGameLogic.WIDTH);
            listList.add(yList);
            for (int x = 0; x < EveFeastGameLogic.WIDTH; x++) {
                EveFeastBlock block = new EveFeastBlock();
                block.setX(x);
                block.setY(y);
                block.setObjectId(0);
                yList.add(block);
            }
        }
        gameData.setBlocks(listList);
        RandomHelper randomHelper = new RandomHelper();
        //初始物品
        for (Integer itemId : config.getTryInitItemIdList()) {
            new EveFeastGameLogic(config, randomHelper).addNewGameItem(gameData, itemId);
        }
        //第一次三选一固定选第一个
        List<Integer> choseList1 = config.getGuideInitSelectItemList().get(0);
        for (Integer itemId : choseList1) {
            gameData.getChoseItems().add(itemId);
        }
        //初始盘面数据消息
        EveFeastProto.EveFeastStartRandomRespMsg.Builder initRespMsg = EveFeastProto.EveFeastStartRandomRespMsg.newBuilder();
        initRespMsg.setRet(0);
        initRespMsg.setGameScene(EveFeastPb.parseGameDataMsg(gameData));

        gameData.getChoseItems().clear();
        Integer firstChoseItem = choseList1.get(0);
        new EveFeastGameLogic(config, randomHelper).addNewGameItem(gameData, firstChoseItem);
        //第一次游宴
        //拼接指定盘面
        JSONArray placeBlockArray = new JSONArray();
        Property firstPlaceProp = config.getGuideSceneProperty().get(0);
        for (Map.Entry<Integer, BigInteger> entry : firstPlaceProp.getGoods().entrySet()) {
            int itemId = entry.getKey();
            int pos = entry.getValue().intValue();
            int y = (pos - 1) / EveFeastGameLogic.WIDTH;
            int x = pos % EveFeastGameLogic.WIDTH;
            if (x == 0) {
                x = EveFeastGameLogic.WIDTH - 1;
            } else {
                x = x - 1;
            }
            for (EveFeastItem haveItem : gameData.getHaveItems()) {
                if (haveItem.getItemId() == itemId) {
                    JSONObject blockJson = new JSONObject();
                    blockJson.put("x", x);
                    blockJson.put("y", y);
                    blockJson.put("id", haveItem.getId());
                    placeBlockArray.add(blockJson);
                }
            }
        }
        EveFeastGameLogic gameLogic = new EveFeastGameLogic(config, randomHelper);
        gameLogic.startRandomPlaceItem(gameData, false, false, JSONObject.toJSONString(placeBlockArray));

        //指定第一次游宴后的可选物品
        gameData.getChoseItems().clear();
        List<Integer> choseList2 = config.getGuideInitSelectItemList().get(1);
        for (Integer itemId : choseList2) {
            gameData.getChoseItems().add(itemId);
        }

        EveFeastProto.EveFeastStartRandomRespMsg.Builder firstRespMsg = EveFeastProto.EveFeastStartRandomRespMsg.newBuilder();
        firstRespMsg.setRet(0);
        firstRespMsg.setGameScene(EveFeastPb.parseGameDataMsg(gameData));
        firstRespMsg.addAllShowGroup(EveFeastPb.parseShowGroupMsg(gameLogic.getShowInfoListList()));
        firstRespMsg.setIsNextRound(gameLogic.isNextRound());
        firstRespMsg.setIsNextTurn(gameLogic.isNextTurn());
        firstRespMsg.setIsEnd(gameLogic.isEnd());
        firstRespMsg.setIsPass(gameLogic.isPass());
        firstRespMsg.setRefreshAdd(gameLogic.getRefreshAdd());
        firstRespMsg.setRemoveAdd(gameLogic.getRemoveAdd());

        //刷新后的三选1,固定选第一个
        gameData.getChoseItems().clear();
        List<Integer> choseList3 = config.getGuideInitSelectItemList().get(2);
        firstChoseItem = choseList3.get(0);
        new EveFeastGameLogic(config, randomHelper).addNewGameItem(gameData, firstChoseItem);

        //第二次游宴
        //拼接指定盘面
        placeBlockArray = new JSONArray();
        Property secondPlaceProp = config.getGuideSceneProperty().get(1);
        for (Map.Entry<Integer, BigInteger> entry : secondPlaceProp.getGoods().entrySet()) {
            int itemId = entry.getKey();
            int pos = entry.getValue().intValue();
            int y = (pos - 1) / EveFeastGameLogic.WIDTH;
            int x = pos % EveFeastGameLogic.WIDTH;
            if (x == 0) {
                x = EveFeastGameLogic.WIDTH - 1;
            } else {
                x = x - 1;
            }
            for (EveFeastItem haveItem : gameData.getHaveItems()) {
                if (haveItem.getItemId() == itemId) {
                    JSONObject blockJson = new JSONObject();
                    blockJson.put("x", x);
                    blockJson.put("y", y);
                    blockJson.put("id", haveItem.getId());
                    placeBlockArray.add(blockJson);
                }
            }
        }
        gameLogic = new EveFeastGameLogic(config, randomHelper);
        gameLogic.startRandomPlaceItem(gameData, false, false, JSONObject.toJSONString(placeBlockArray));

        EveFeastProto.EveFeastStartRandomRespMsg.Builder secondRespMsg = EveFeastProto.EveFeastStartRandomRespMsg.newBuilder();
        secondRespMsg.setRet(0);
        secondRespMsg.setGameScene(EveFeastPb.parseGameDataMsg(gameData));
        secondRespMsg.addAllShowGroup(EveFeastPb.parseShowGroupMsg(gameLogic.getShowInfoListList()));
        secondRespMsg.setIsNextRound(gameLogic.isNextRound());
        secondRespMsg.setIsNextTurn(gameLogic.isNextTurn());
        secondRespMsg.setIsEnd(gameLogic.isEnd());
        secondRespMsg.setIsPass(gameLogic.isPass());
        secondRespMsg.setRefreshAdd(gameLogic.getRefreshAdd());
        secondRespMsg.setRemoveAdd(gameLogic.getRemoveAdd());

        guideMsgList.clear();
        guideMsgList.add(initRespMsg.build());
        guideMsgList.add(firstRespMsg.build());
        guideMsgList.add(secondRespMsg.build());
        initGameData = gameData;
    }

    public static List<EveFeastProto.EveFeastStartRandomRespMsg> getGuideMsgList() {
        return guideMsgList;
    }

    public static EveFeastGameData getInitGameData() {
        return initGameData;
    }
}
